package com.aviation.sell_ticket.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aviation.sell_ticket.mapper.CityMapper;
import com.aviation.sell_ticket.pojo.Aviation_city;
import com.aviation.sell_ticket.service.CityService;
import com.aviation.sell_ticket.tool.RedisUtil;
import com.aviation.sell_ticket.tool.ResultEnum;
import com.aviation.sell_ticket.tool.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CityServiceImpl implements CityService {

    @Resource
    private CityMapper cityMapper;

    @Resource
    private RedisUtil redis;//引入redis

    /**
     * 查询机场城市
     * @return Map<String,Object>
     */
    @Override
    public Map<String,Object> getCity() {
        JSONArray cityArray=null;
        try {
            //从缓存中提取数据
            String cityData = redis.getRedis("city");
            //判断缓存是否存在
            if (null == cityData) {
                //从数据库提取数据
                List<Aviation_city> cityList = cityMapper.getCity();
                //转换json
                cityArray = JSONArray.parseArray(JSON.toJSONString(cityList));
                //添加数据进缓存
                redis.setRidesTime("city",cityArray.toJSONString(),(long) (60 * 60), TimeUnit.SECONDS);
            }else {
                //缓存中有数据，转成json
                List<Aviation_city> cityList= JSONArray.parseArray(cityData,Aviation_city.class);
                cityArray = JSONArray.parseArray(JSON.toJSONString(cityList));
            }
        }catch (Exception e){
            return ResultUtil.beDefeated(ResultEnum.UNKNOWN_ERROR);
        }
        return ResultUtil.success(ResultEnum.SUCCESS, cityArray);
    }

    /**
     * 使用城市名称查询城市信息
     * @param cityName 城市名称
     * @return Aviation_city
     */
    @Override
    public Aviation_city obtainCity(String cityName) {
        return cityMapper.obtainCity(cityName);
    }

    /**
     * 根据城市Id查询城市信息
     * @param cityId 城市id
     * @return Aviation_city
     */
    @Override
    public Aviation_city transferCity(Integer cityId) {
        return cityMapper.transferCity(cityId);
    }

}
